<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/11/13
 * Time: 上午11:33
 */

namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function index()
    {
        return view('main::article', \Request::all());
    }

    public function category()
    {
        $data['items'] = Article::whereNull('parent_id')->where('is_category', 1)->get(['id', 'title']);

        return success($data);
    }

    public function article($id)
    {
        $data['items'] = Article::where('parent_id', $id)->where('is_category', 0)->get(['id', 'title', 'intro']);

        return success($data);
    }

    public function all()
    {
        $data['items'] = Article::whereNull('parent_id')->with([
            'articles' => function($q) {
                $q->select('id', 'parent_id', 'title', 'intro', 'is_category');
            }
        ])->where('is_category', 1)->get(['id', 'title', 'is_category', 'parent_id', 'intro']);
        return success($data);
    }

    public function store(Request $request)
    {
        $parent_id   = $request->input('parent_id', null);
        $is_category = $request->input('is_category', 0);
        $title       = $request->input('title');
        $intro       = $request->input('intro');

        if (!$title) {
            return fail(400, '参数错误');
        }
        if (!$is_category && !$intro) {
            return fail(400, '参数错误');
        }

        Article::create([
            'parent_id'   => $parent_id ? : null,
            'is_category' => $is_category,
            'title'       => $title,
            'intro'       => $intro,
        ]);

        return success();
    }

    public function update(Request $request, $id)
    {
        $article = Article::find($id);
        if (!$article) {
            return fail(404, '未找到记录');
        }

        if ($request->has('parent_id')) {
            $article->parent_id = $request->input('parent_id') ? : null;
        }
        if ($request->has('title') && $request->input('title')) {
            $article->title = $request->input('title');
        }
        if ($request->has('intro') && $request->input('intro')) {
            $article->intro = $request->input('intro');
        }

        $article->save();

        return success();
    }

    public function destroy($id)
    {
        $article = Article::find($id);
        if (!$article) {
            return fail(404, '未找到记录');
        }
        $article->delete();

        return success();
    }
}